<template>
    <el-tabs v-model="state.activeName" class="demo-tabs" @tab-click="handleClick">
        <el-tab-pane label="文件略缩图" name="first">
            <div class="m-3 inline-block" v-for="item in state.data">
                <el-badge :value="item.children.length">
                    <el-button @click="checkFiles(item)" :icon="Folder" :type="item.children.length>0 ?'warning':''">{{item.label}}
                    </el-button>
                </el-badge>
            </div>

            <div class="pt-8 flex">
                <div v-for="file in state.files" :key="file.label" class="flex flex-col px-2">
                    <div v-if="getFileType(file.label)"
                        class="w-100px h-50px text-center leading-50px my-25px bg-gray-300 text-white">
                        {{getFileType(file.label)}}</div>
                    <el-image v-else class="m-auto" style="width: 100px; height: 100px"
                        :src="baseURL + '/upload/' + state.directoryName + '/' + file.label" fit="contain" />
                    <span class="text-gray-500 text-xs">{{ file.label }}</span>
                    <div class="flex text-xs">
                        <span @click="viewDetail(file.label)" class="cursor-pointer pr-2 text-blue-500">查看</span>
                        <span @click="download(baseURL + '/upload/' + state.directoryName + '/' + file.label, file.label)" class="cursor-pointer pr-2 text-gray-500">下载</span>
                        <span @click="handleDelete('/upload/' + state.directoryName + '/' + file.label)" class="cursor-pointer text-red-500">删除</span>
                    </div>
                </div>
                <el-empty class="w-1/1" v-if="state.files.length == 0" description="空目录" />
            </div>
        </el-tab-pane>
        <el-tab-pane label="文件树" name="second">
            <el-tree :data="state.data" :props="defaultProps" @node-click="handleNodeClick" />
        </el-tab-pane>

        <el-dialog v-model="state.dialogVisible" title="信息">
            <p>标题：{{ state.dialogInfo.title}}</p>
            <p>上传时间：{{ state.dialogInfo.createAt}}</p>
            <el-link :href="'/#/detail/' + state.dialogInfo.id" type="primary">跳转详情页</el-link>
            <!-- <p>上传者：{{ state.dialogInfo.title}}</p> -->
        </el-dialog>
    </el-tabs>
</template>

<script lang="ts" setup>
import { httpFileTree, httpFileDelete, httpFileDetail } from '@/api/file'
import { onMounted, reactive } from 'vue'
import { Folder } from '@element-plus/icons-vue'
import type { TabsPaneContext } from 'element-plus'
import { ElMessage, ElMessageBox } from 'element-plus'
import { baseURL } from '@/config/index'
import useCurrentInstance from "@/utils/useCurrentInstance"
const { proxy } = useCurrentInstance()

interface Tree {
    label: string,
    children: Tree[]
}
interface FileDetail{
    id:number,
    title:string,
    createAt:string
}

const handleNodeClick = (data: Tree) => {
    console.log(data)
}

const state = reactive({
    data: [] as Tree[],
    activeName: 'first',
    files: [] as Tree[],
    directoryName: '',
    dialogVisible:false,
    dialogInfo:{} as FileDetail
})

// 查看
const viewDetail = async (name: string) => {
    state.dialogVisible = true
    const res:any = await httpFileDetail({ name })
    if(res.code === 200){
        state.dialogInfo.id = res.data.id
        state.dialogInfo.title = res.data.title
        state.dialogInfo.createAt = res.data.createAt
    }
}

// 删除文件
const handleDelete = (url: string) => {
    ElMessageBox.confirm('是否删除该文件', 'Title', {}).then(() => {
        httpFileDelete({ url }).then((res: any) => {
            if (res.code === 200) {
                ElMessage.success('删除成功')
                getFileTree()
            }
        })
    }).catch(() => {
        console.log('取消')
    })
}

// 下载
const download = (url: string, title: string) => {
    fetch(url).then(res => res.blob().then(blob => {
        const a = document.createElement('a')
        const url = window.URL.createObjectURL(blob)
        const filename = title
        a.href = url
        a.download = filename
        a.click()
        window.URL.revokeObjectURL(url)
    }))
}


//  获取文件类型
const getFileType = (fileName: string) => {
    let o = fileName.split('').reverse().join('')
    let type = o.substring(0, o.search(/\./)).split('').reverse().join('')

    const strFilter = ['jpg', 'jpeg', 'png', 'svg', 'gif']
    if (strFilter.indexOf(type) > -1) {
        return false
    }
    return type
}

// 点击查看文件夹
const checkFiles = (directory: any) => {
    state.files = directory.children
    state.directoryName = directory.label
}

const handleClick = (tab: TabsPaneContext, event: Event) => {
    // console.log(tab, event)
}

// 树状props
const defaultProps = {
    children: 'children',
    label: 'label',
}

// 获取文件列表
const getFileTree = () => {
    httpFileTree().then((res: any) => {
        if (res.code === 200) {
            state.data = res.data
            if (res.data.length > 0) {
                state.files = res.data[0].children
                state.directoryName = state.data[0].label
            }
        }
    })
}

onMounted(() => {
    getFileTree()
})

</script>
